package utils;

import java.sql.*;

public class DBConnectionUtil {
    static final String URL = "jdbc:mysql://localhost:3306/student?useSSL=false";
    static final String USER = "root";
    static final String PSW = "123456789";
    // mysql连接驱动
    static String DRIVER = "com.mysql.cj.jdbc.Driver";
    static Connection conn;
    static ResultSet rs = null;
    static PreparedStatement ps = null;

    public static void init() {
        try {
            // 加载数据库驱动
            Class.forName(DRIVER);

            // 建立连接
            conn = DriverManager.getConnection(URL, USER, PSW);
        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动加载异常");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("数据库连接异常");
            e.printStackTrace();
        }
    }

    /**
     * sql查询
     * @param sql 要查询的sql
     * @return
     */
    public static ResultSet select(String sql) {
        try {
            // 获取预编译对象
            ps = conn.prepareStatement(sql);

            rs = ps.executeQuery();
        } catch (SQLException e) {
            System.out.println("数据库查询异常");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 数据库更新: add, update, delete
     * @param sql
     * @return
     */
    public static int update(String sql) {
        int i = 0;
        try {
            ps = conn.prepareStatement(sql);
            boolean flag = ps.execute(); // 如果第一个结果是结果集对象，则返回true;如果第一个结果是更新计数或者没有结果，则返回false
            if (flag == false) i++;
        } catch (SQLException e) {
            System.out.println("数据库更新异常");
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 数据库关闭
     */
    public static void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            System.out.println("数据库关闭异常");
            e.printStackTrace();
        }
    }
}
